package src.main.java.com.pms.gui.dialog.sale;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import src.main.java.com.pms.service.SaleService;

public class CancelSaleDialog extends JDialog {
    private JTextField petIdField;
    private SaleService saleService;

    public CancelSaleDialog(JFrame parent) {
        super(parent, "取消寄卖", true);
        saleService = new SaleService();
        initComponents();
        setVisible(true); // 显示对话框
        petIdField.requestFocusInWindow(); // 确保宠物ID输入框获得焦点
    }

    private void initComponents() {
        setSize(300, 150);
        setLocationRelativeTo(getParent());

        JPanel panel = new JPanel(new GridLayout(2, 2, 10, 10));

        JLabel petIdLabel = new JLabel("宠物ID:");
        petIdField = new JTextField();

        JButton cancelButton = new JButton("取消寄卖");
        cancelButton.addActionListener(new CancelActionListener());

        panel.add(petIdLabel);
        panel.add(petIdField);
        panel.add(new JLabel()); // Empty label for spacing
        panel.add(cancelButton);

        add(panel);
    }


    private class CancelActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int petId = Integer.parseInt(petIdField.getText().trim());

                if (petId <= 0) {
                    JOptionPane.showMessageDialog(CancelSaleDialog.this, "请输入有效的宠物ID", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                saleService.cancelPetSale(petId);
                JOptionPane.showMessageDialog(CancelSaleDialog.this, "寄卖取消成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(CancelSaleDialog.this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
